package com.orange.msm.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author orange
 * @email orangestart@yeah.net
 * @create 2021-12-23 22:36
 */
public class EmailUtil {

    public static boolean sendEmail(String code, String to) {
        // 收件人电子邮箱
        // String to = "orangestart@yeah.net";
        // 发件人电子邮箱
        String from = "1639937877@qq.com";
        // 指定发送邮件的主机为 smtp.qq.com, QQ 邮件服务器
        String host = "smtp.qq.com";
        // qq邮箱授权码，要用自己的，每个邮箱都不一样
        String authorizationCode = "lsmhcdteffpydggd";
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮件用户名、授权码
                return new PasswordAuthentication(from, authorizationCode);
            }
        });
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // Set Subject: 标题
            message.setSubject("【橙子学苑】");
            // 设置消息体 code:【验证码】
            String messBody = "验证码：" + code + "，您正在进行身份验证，5分钟内有效，打死不要告诉别人哦(⊙o⊙)！";
            message.setText(messBody);
            // 发送消息
            Transport.send(message);
//            System.out.println("Sent Email successfully....");
        } catch (MessagingException mex) {
            return false;
        }
        return true;
    }
}
